import { state } from './state'
import Tab from './Tab'
import { BrowserWindow, NewWindowEvent } from 'electron'
import { toRaw } from 'vue'
import evtBus from '@/common/evtButs'
const { Menu, app, Tray, BrowserWindow: RBrowserWindow } = window.require('electron').remote
const { BrowserView } = window.require('electron').remote
const win: BrowserWindow = window.require('electron').remote.getCurrentWindow()
let appTray: any

win.on('new-window-for-tab', () => {
  alert('new-window-for-tab')
})

export default {
  addTab({ url = '', index = state.tabs.length, disposition = 'foreground-tab', webSecurity = true, nodeIntegration = false, frameName }: { frameName?: string; nodeIntegration?: boolean; webSecurity?: boolean; url?: string; index?: number; disposition?: 'foreground-tab' | 'background-tab' | 'new-window' } = {}) {
    if (frameName) {
      for (let i = 0; i < state.tabs.length; i++) {
        const tab = state.tabs[i]
        if (tab.frameName === frameName) {
          tab.view.webContents.loadURL(url)
          state.tabIndex = i
          return
        }
      }
    }

    const tab: Tab = {
      id: Math.random()
        .toString(36)
        .substr(2),
      url,
      title: url || '新建标签页',
      view: new BrowserView({
        webPreferences: {
          nodeIntegration,
          webSecurity
        }
      }),
      canGoBack: false,
      canGoForward: false,
      favicons: null,
      isLoading: false,
      frameName
    }
    state.tabs.splice(index, 0, tab)
    const tabRe = state.tabs[index]
    switch (disposition) {
      case 'foreground-tab':
      case 'new-window':
        state.tabIndex = index
        break
      case 'background-tab':
        if (index <= state.tabIndex) {
          state.tabIndex++
        }
        break
    }

    tab.view.webContents.on('did-start-loading', (evt: any) => {
      console.log('did-start-loading')
      tabRe.isLoading = true
    })
    tab.view.webContents.on('did-start-navigation', (evt: any, url: string, isInPlace: boolean, isMainFrame: boolean, frameProcessId: number, frameRoutingId: number) => {
      if (isMainFrame) {
        tabRe.url = url
      }
      evtBus.emit('tab-did-start-navigation', { tab, evt, url, isInPlace, isMainFrame, frameProcessId, frameRoutingId })
      console.log('did-start-navigation')
    })

    tab.view.webContents.on('page-title-updated', (evt: any, title: string, explicitSet: boolean) => {
      tabRe.title = title
      tabRe.canGoBack = tab.view.webContents.canGoBack()
      tabRe.canGoForward = tab.view.webContents.canGoForward()
      tabRe.url = tab.view.webContents.getURL()
      tabRe.favicons = null
      evtBus.emit('tab-page-title-updated', { tab, evt, title, explicitSet })
      console.log('page-title-updated')
    })
    tab.view.webContents.on('dom-ready', (evt: any) => {
      evtBus.emit('tab-dom-ready', { tab, evt })
      console.log('dom-ready')
    })

    tab.view.webContents.on('page-favicon-updated', (evt: any, favicons: string[]) => {
      tabRe.favicons = favicons
      evtBus.emit('tab-page-favicon-updated', { tab, evt, favicons })
      console.log('page-favicon-updated')
    })

    tab.view.webContents.on('did-stop-loading', (evt: any) => {
      console.log('did-stop-loading')
      tabRe.isLoading = false
    })

    tab.view.webContents.on('new-window', (evt: NewWindowEvent, url: string, frameName: string, disposition: 'default' | 'foreground-tab' | 'background-tab' | 'new-window' | 'save-to-disk' | 'other') => {
      evt.preventDefault()
      // #TODO disposition = new-window无法处理
      switch (disposition) {
        case 'foreground-tab':
        case 'background-tab':
        case 'new-window':
          this.addTab({ url, index: state.tabIndex + 1, disposition, frameName })
          break
        default:
          alert('unknow disposition:' + disposition)
          break
      }
      evtBus.emit('tab-new-window', { tab, evt, url, frameName, disposition })
      console.log('new-window')
    })

    tab.view.webContents.on('enter-html-full-screen', () => {
      // state.isFullScreen = true
      evtBus.emit('tab-enter-html-full-screen', { tab })
      console.log('enter-html-full-screen')
    })
    tab.view.webContents.on('leave-html-full-screen', () => {
      // state.isFullScreen = false
      evtBus.emit('tab-leave-html-full-screen', { tab })
      console.log('leave-html-full-screen')
    })

    if (tab.url) {
      tab.view.webContents.loadURL(tab.url)
    } else {
      tab.view.webContents.loadURL('zchrome-search://local-ntp/local-ntp.html')
    }
    return tab
  },
  close() {
    win.webContents.closeDevTools()
    win.close()
  },
  async tray() {
    if (!appTray) {
      let path = app.getAppPath()
      path = path.substr(0, path.length - 18) + app.name + '.exe'
      console.log(path)
      const icon = await app.getFileIcon(path)
      appTray = new Tray(icon)
      const contextMenu = Menu.buildFromTemplate([
        {
          label: '显示主界面',
          click: () => {
            win.show()
            win.focus()
          }
        },
        {
          label: '退出',
          click: () => {
            this.close()
          }
        }
      ])

      appTray.setContextMenu(contextMenu)
    }
    win.hide()
  },

  async removeTab(index: number) {
    if (state.tabs.length === 1 && index === 0) {
      this.close()
      return
    }
    const tab = state.tabs.splice(index, 1)[0]
    if (state.tabs.length <= state.tabIndex) {
      state.tabIndex = state.tabs.length - 1
    }
    win.removeBrowserView(toRaw(tab.view))
    tab.view.destroy()
  },

  wCurTab() {
    const tab = state.tabs[state.tabIndex]
    win.setBrowserView(toRaw(tab.view))
    this.contentViewAutoResize(tab)
  },

  contentViewAutoResize(tab: Tab) {
    const size = win.getContentSize()
    let topViewHeight = 81
    if (state.isMaximized) {
      topViewHeight -= 8
    }
    if (state.isFullScreen) {
      topViewHeight = 0
    }
    tab.view.setBounds({
      x: 0,
      y: topViewHeight,
      width: size[0],
      height: size[1] - topViewHeight
    })
    tab.view.setAutoResize({ width: true, height: true, horizontal: true, vertical: false })
  }
}
